<template>
  <div :style="{ ...coreStyle.marginSame(8) }">
    <a-card>
      <a-form ref="dbTableFormQueryRef" :model="dbTableFormQueryModel" labelAlign="left" layout="vertical" :style="{ ...coreStyle.marginBottom(10) }">
        <a-row :gutter="16" v-show="!dbTableFormQueryVisible">
          <a-col :span="8">
            <a-form-item :style="{ ...coreStyle.marginBottom(-8) }">
              <a-input-search v-model:value="dbTableFormQueryModel.keySearchVo" placeholder="关键字搜索" :disabled="dbTableFormQuerySubmitting" @search="dbTableFormQuerySearch" />
            </a-form-item>
          </a-col>
          <a-col :span="16">
            <a-button type="link" :style="{ ...coreStyle.floatRight }" @click="dbTableFormQueryUpDown">
              展开
              <CoreIcon icon="akar-icons:chevron-down" :size="14" />
            </a-button>
          </a-col>
        </a-row>
        <a-row :gutter="16" v-show="dbTableFormQueryVisible">
          <a-col :span="8">
            <a-form-item>
              <a-input-search v-model:value="dbTableFormQueryModel.keySearchVo" placeholder="关键字搜索" :disabled="dbTableFormQuerySubmitting" @search="dbTableFormQuerySearch" />
            </a-form-item>
          </a-col>
          <a-col :span="16">
          </a-col>
          <a-col :span="8">
            <a-form-item label="表名注释">
              <a-input v-model:value="dbTableFormQueryModel.tableNameAnnotationAndLike" placeholder="输入表名注释" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="数据库表前缀">
              <a-input v-model:value="dbTableFormQueryModel.dbTablePrefixAndLike" placeholder="输入数据库表前缀" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="数据库表分组">
              <a-input v-model:value="dbTableFormQueryModel.dbTableGroupingAndLike" placeholder="输入数据库表分组" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="排序权重">
              <a-input-number v-model:value="dbTableFormQueryModel.weightOrder" :style="{ ...coreStyle.width('100%') }" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-space :style="{ ...coreStyle.floatRight }">
              <a-button @click="dbTableFormQueryReset">
                <CoreIcon icon="ant-design:clear-outlined" :size="14" />
                重置
              </a-button>
              <a-button type="primary" ghost :loading="dbTableFormQuerySubmitting" @click="dbTableFormQuerySearch">
                <CoreIcon icon="ant-design:search-outlined" :size="14" />
                查询
              </a-button>
              <a-button type="link" @click="dbTableFormQueryUpDown">
                收起
                <CoreIcon icon="akar-icons:chevron-up" :size="14" />
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
      <a-space>
        <a-button type="primary" ghost @click="dbTableAdd">
          <CoreIcon icon="carbon:add-alt" :size="14" />
          新增
        </a-button>
        <a-button type="dashed" @click="dbTableUpdate" v-if="dbTableListSelectLength === 1">
          <CoreIcon icon="ri:brush-line" :size="14" />
          修改
        </a-button>
        <a-popconfirm title="确认删除？" placement="bottom" @confirm="dbTableDelete" v-if="dbTableListSelectLength > 0">
          <a-button type="dashed" danger>
            <CoreIcon icon="jam:delete" :size="14" />
            删除
          </a-button>
        </a-popconfirm>
        <a-button @click="dbTableDetailInfo" v-if="dbTableListSelectLength === 1">
          <CoreIcon icon="heroicons-outline:light-bulb" :size="14" />
          详情
        </a-button>
      </a-space>
      <a-space :style="{ ...coreStyle.floatRight }">
        <a-button type="link" shape="circle" @click="dbTableListGetDataSet">
          <CoreIcon icon="ci:refresh" :size="22" />
        </a-button>
      </a-space>
      <a-table
        rowKey="id"
        :columns="dbTableListColumns"
        :data-source="dbTableListDataSet"
        :loading="dbTableListLoading"
        :pagination="false"
        bordered
        :customRow="dbTableListCustomRow"
        :row-selection="{ fixed: true, selectedRowKeys: dbTableListSelectedRowKeys, onChange: dbTableListRowOnChange }"
        :scroll="{ x: '100%', y: 550 }"
        :style="{ ...coreStyle.marginTop(10) }"
      >
      </a-table>
      <a-pagination
        v-model:current="dbTableListDataPage"
        v-model:pageSize="dbTableListDataRows"
        :total="dbTableListDataCount"
        show-size-changer
        show-quick-jumper
        :page-size-options="[ ...coreStyle.antdPaginationPageSizeOptions ]"
        :show-total="(total, range) => coreStyle.antdPaginationShowTotal(total, range)"
        :style="{ ...coreStyle.marginTop(10), ...coreStyle.textAlignCenter }"
        @change="dbTableListPaginationChange"
        @showSizeChange="dbTableListPaginationShowSizeChange"
        v-if="dbTableListPaginationVisible"
      >
      </a-pagination>
      <p :style="{ ...coreStyle.marginTop(14), ...coreStyle.marginBottom(6), ...coreStyle.textAlignCenter }" v-if="!dbTableListPaginationVisible">
        {{ coreStyle.antdPaginationShowTotal(dbTableListDataCount) }}
      </p>
    </a-card>
    <a-drawer
      v-model:visible="dbTableEditDrawerVisible"
      title="编辑数据库表信息"
      placement="right"
      :closable="false"
      :width="'40%'"
      :header-style="{ ...coreStyle.antdDrawerHeader }"
      :body-style="{ ...coreStyle.margin(50, 0, 30, 0) }"
      @close="dbTableEditDrawerOnClose"
    >
      <a-form ref="dbTableFormRef" :model="dbTableFormModel" :rules="dbTableFormRules" labelAlign="left" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="表名注释" name="tableNameAnnotation">
              <a-input v-model:value="dbTableFormModel.tableNameAnnotation" placeholder="输入表名注释" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="数据库表前缀" name="dbTablePrefix">
              <a-input v-model:value="dbTableFormModel.dbTablePrefix" placeholder="输入数据库表前缀" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="数据库表分组" name="dbTableGrouping">
              <a-input v-model:value="dbTableFormModel.dbTableGrouping" placeholder="输入数据库表分组" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="排序权重" name="weightOrder">
              <a-input-number v-model:value="dbTableFormModel.weightOrder" :style="{ ...coreStyle.width('100%') }" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div :style="{ ...coreStyle.antdDrawerFooter }">
        <a-space>
          <a-button @click="dbTableFormReset">
            <CoreIcon icon="ant-design:clear-outlined" :size="14" />
            重置
          </a-button>
          <a-button type="primary" ghost :loading="dbTableFormSaveSubmitting" @click="dbTableFormNextAdd">
            <CoreIcon icon="tabler:player-track-next" :size="14" />
            继续录入
          </a-button>
          <a-button type="primary" ghost :loading="dbTableFormSaveSubmitting" @click="dbTableFormSave">
            <CoreIcon icon="ant-design:save-outlined" :size="14" />
            保存
          </a-button>
        </a-space>
      </div>
    </a-drawer>
    <a-drawer
      v-model:visible="dbTableDetailDrawerVisible"
      title="数据库表详细信息"
      placement="right"
      :closable="false"
      :width="'40%'"
      :header-style="{ ...coreStyle.antdDrawerHeader }"
      :body-style="{ ...coreStyle.margin(50, 0, 30, 0) }"
    >
      <a-space direction="vertical" :size="20" :style="{ ...coreStyle.width('100%') }">
        <a-descriptions title="基础信息" :column="2" bordered>
          <a-descriptions-item label="表名注释" :span="1">{{ dbTableDetailModel.tableNameAnnotation }}</a-descriptions-item>
          <a-descriptions-item label="数据库表前缀" :span="1">{{ dbTableDetailModel.dbTablePrefix }}</a-descriptions-item>
          <a-descriptions-item label="数据库表分组" :span="1">{{ dbTableDetailModel.dbTableGrouping }}</a-descriptions-item>
          <a-descriptions-item label="排序权重" :span="1">{{ dbTableDetailModel.weightOrder }}</a-descriptions-item>
        </a-descriptions>
      </a-space>
      <div :style="{ ...coreStyle.antdDrawerFooter }">
        <a-space>
          <a-button type="dashed" @click="dbTableDetailUpdate">
            <CoreIcon icon="ri:brush-line" :size="14" />
            修改
          </a-button>
        </a-space>
      </div>
    </a-drawer>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from 'vue-class-component'
import { mapStores } from 'pinia'
import { useCoreToolStore } from '/@/store/modules/cn/core/tool/coreToolStore'
import type { Res } from '/@/tool/Res'
import type { Param } from '/@/tool/Param'

import { useDbTableStore } from '/@/store/modules/cn/core/data/dbTableStore'

import type { DbTable } from '/@/model/cn/core/data/eo/DbTable'
import { toDbTable } from '/@/model/cn/core/data/eo/DbTable'

import type { DbTableQO } from '/@/model/cn/core/data/qo/DbTableQO'
import { toDbTableQO } from '/@/model/cn/core/data/qo/DbTableQO'

import type { DbTableVO } from '/@/model/cn/core/data/vo/DbTableVO'
import { toDbTableVO } from '/@/model/cn/core/data/vo/DbTableVO'

@Options({
  name: 'DbTable',
  components: {
  },
  computed: {
    ...mapStores(useCoreToolStore, useDbTableStore),
  },
})
export default class DbTable extends Vue {

  dbTableListDataSet: Array<DbTableVO> = []

  dbTableListColumns: Array<object> = [
    {
      title: '表名注释',
      dataIndex: 'tableNameAnnotation',
      align: 'center',
      // ellipsis: true,
      // width: 200,
    },
    {
      title: '数据库表前缀',
      dataIndex: 'dbTablePrefix',
      align: 'center',
      // ellipsis: true,
      // width: 200,
    },
    {
      title: '数据库表分组',
      dataIndex: 'dbTableGrouping',
      align: 'center',
      // ellipsis: true,
      // width: 200,
    },
    {
      title: '排序权重',
      dataIndex: 'weightOrder',
      align: 'center',
      // ellipsis: true,
      // width: 200,
    },
  ]

  dbTableListLoading: boolean = false

  dbTableListSelectedRowKeys: string[] = []

  dbTableListSelectData: Array<DbTableVO> = []

  dbTableListSelectLength: number = 0

  dbTableListSelectCurrentRowIndex: number = -1

  dbTableListSelectCurrentRowData: DbTableVO = toDbTableVO()

  dbTableListPaginationVisible: boolean = true

  dbTableListDataPage: number = 1

  dbTableListDataRows: number = 10

  dbTableListDataCount: number = 0

  dbTableListRowOnChange(selectedRowKeys, selectedRows) {
    this.dbTableListSelectedRowKeys = [ ...selectedRowKeys ]
    this.dbTableListSelectData = [ ...selectedRows ]
    this.dbTableListSelectLength = selectedRows.length
  }

  dbTableListCustomRow(record, index) {
    return {
      'class': index === this.dbTableListSelectCurrentRowIndex ? 'ant-table-row-selected' : '',
      onClick: (event) => {
        this.dbTableListSelectCurrentRowIndex = index
        this.dbTableListSelectCurrentRowData = { ...record }
        let selectedRowKeys = [ ...this.dbTableListSelectedRowKeys ]
        let selectedRows = [ ...this.dbTableListSelectData ]
        if (selectedRowKeys.includes(record.id)) {
          this.dbTableListRowOnChange([ ...selectedRowKeys.filter(eo => { return eo !== record.id }) ], [ ...selectedRows.filter(eo => { return eo.id !== record.id }) ])
        } else {
          selectedRowKeys.push(record.id)
          selectedRows.push(record)
          this.dbTableListRowOnChange([ ...new Set(selectedRowKeys) ], [ ...new Set(selectedRows) ])
        }
      },
      onDblclick: (event) => {
        this.dbTableStore.pkVo(this.$toParam<DbTableQO>({ id: this.dbTableListSelectCurrentRowData.id } as DbTableQO)).then((res: Res<DbTableVO>) => {
          if (res.succ) {
            this.dbTableDetailModel = { ...res.data[0] }
            this.dbTableDetailDrawerVisible = true
          } else {
            this.$message.error(res.msg, 6)
          }
        })
      },
    }
  }

  dbTableListGetDataSet() {
    this.dbTableListLoading = true
    this.dbTableListRowOnChange([], [])
    this.dbTableListSelectCurrentRowIndex = -1
    this.dbTableListSelectCurrentRowData = toDbTableVO()
    this.dbTableStore.pagingVo(this.$toParam<DbTableQO>([], this.dbTableListDataPage, this.dbTableListDataRows)).then((res: Res<DbTableVO>) => {
      if (res.succ) {
        this.dbTableListPaginationVisible = true
        this.dbTableListDataSet = [ ...res.data ]
        this.dbTableListDataCount = res.count
        setTimeout(() => { this.dbTableListLoading = false }, 500)
      } else {
        this.$message.error(res.msg, 6)
        setTimeout(() => { this.dbTableListLoading = false }, 500)
      }
    }).catch(err => {
      setTimeout(() => { this.dbTableListLoading = false }, 500)
    })
  }

  dbTableListPaginationChange() {
    this.dbTableListGetDataSet()
  }

  dbTableListPaginationShowSizeChange() {
    this.dbTableListGetDataSet()
  }

  dbTableFormQueryVisible: boolean = false

  dbTableFormQuerySubmitting: boolean = false

  dbTableFormQueryModel: DbTableQO = toDbTableQO()

  dbTableFormQueryUpDown() {
    this.dbTableFormQueryVisible = !this.dbTableFormQueryVisible
  }

  dbTableFormQueryReset() {
    if (this.$refs.dbTableFormQueryRef) {
      this.$refs.dbTableFormQueryRef.resetFields()
      this.dbTableFormQueryModel = toDbTableQO()
    }
  }

  dbTableFormQuerySearch() {
    this.dbTableFormQuerySubmitting = true
    this.dbTableListLoading = true
    this.dbTableListRowOnChange([], [])
    this.dbTableListSelectCurrentRowIndex = -1
    this.dbTableListSelectCurrentRowData = toDbTableVO()
    this.dbTableStore.queryVo(this.$toParam<DbTableQO>(this.$toSearch({ ...this.dbTableFormQueryModel }))).then((res: Res<DbTableVO>) => {
      if (res.succ) {
        this.dbTableListPaginationVisible = false
        this.dbTableListDataSet = [ ...res.data ]
        this.dbTableListDataCount = res.count
        setTimeout(() => { this.dbTableFormQuerySubmitting = false }, 5000)
        setTimeout(() => { this.dbTableListLoading = false }, 500)
      } else {
        this.$message.error(res.msg, 6)
        setTimeout(() => { this.dbTableFormQuerySubmitting = false }, 5000)
        setTimeout(() => { this.dbTableListLoading = false }, 500)
      }
    }).catch(err => {
      setTimeout(() => { this.dbTableFormQuerySubmitting = false }, 5000)
      setTimeout(() => { this.dbTableListLoading = false }, 500)
    })
  }

  dbTableEditDrawerVisible: boolean = false

  dbTableFormSaveSubmitting: boolean = false

  dbTableFormSaveContinue: boolean = false

  dbTableFormModel: DbTable = toDbTable()

  dbTableFormRules: object = {
    // tableNameAnnotation: [
    //   { type: 'string', required: true, message: '表名注释不能为空！', trigger: ['change', 'blur'] },
    // ],
    // dbTablePrefix: [
    //   { type: 'string', required: true, message: '数据库表前缀不能为空！', trigger: ['change', 'blur'] },
    // ],
    // dbTableGrouping: [
    //   { type: 'string', required: true, message: '数据库表分组不能为空！', trigger: ['change', 'blur'] },
    // ],
    // weightOrder: [
    //   { type: 'number', required: true, message: '排序权重不能为空！', trigger: ['change', 'blur'] },
    // ],
  }

  dbTableFormReset() {
    if (this.$refs.dbTableFormRef) {
      this.$refs.dbTableFormRef.resetFields()
      this.dbTableFormModel = toDbTable()
    }
  }

  dbTableFormSubmit() {
    this.dbTableFormSaveSubmitting = true
    this.$refs.dbTableFormRef.validate().then(() => {
      if (this.dbTableFormModel.id) {
        this.dbTableStore.update(this.$toParam<DbTable>(this.dbTableFormModel)).then((res: Res<DbTable>) => {
          if (res.succ) {
            this.$message.success(res.msg, 3)
            this.dbTableFormReset()
            this.dbTableFormSaveSubmitting = false
            if (!this.dbTableFormSaveContinue) {
              this.dbTableEditDrawerVisible = false
              this.dbTableListGetDataSet()
            }
          } else {
            this.$message.error(res.msg, 6)
            setTimeout(() => { this.dbTableFormSaveSubmitting = false }, 3000)
          }
        }).catch(err => {
          setTimeout(() => { this.dbTableFormSaveSubmitting = false }, 3000)
        })
      } else {
        this.dbTableStore.save(this.$toParam<DbTable>(this.dbTableFormModel)).then((res: Res<DbTable>) => {
          if (res.succ) {
            this.$message.success(res.msg, 3)
            this.dbTableFormReset()
            this.dbTableFormSaveSubmitting = false
            if (!this.dbTableFormSaveContinue) {
              this.dbTableEditDrawerVisible = false
              this.dbTableListGetDataSet()
            }
          } else {
            this.$message.error(res.msg, 6)
            setTimeout(() => { this.dbTableFormSaveSubmitting = false }, 3000)
          }
        }).catch(err => {
          setTimeout(() => { this.dbTableFormSaveSubmitting = false }, 3000)
        })
      }
    }).catch(() => {
      setTimeout(() => { this.dbTableFormSaveSubmitting = false }, 3000)
    })
  }

  dbTableFormSave() {
    this.dbTableFormSaveContinue = false
    this.dbTableFormSubmit()
  }

  dbTableFormNextAdd() {
    this.dbTableFormSaveContinue = true
    this.dbTableFormSubmit()
  }

  dbTableAdd() {
    if (this.dbTableFormModel.id) {
      this.dbTableFormReset()
    }
    this.dbTableEditDrawerVisible = true
  }

  dbTableUpdate() {
    this.dbTableStore.pk(this.$toParam<DbTableQO>({ id: this.dbTableListSelectData[0].id } as DbTableQO)).then((res: Res<DbTable>) => {
      if (res.succ) {
        this.dbTableFormReset()
        this.dbTableFormModel = { ...res.data[0] }
        this.dbTableEditDrawerVisible = true
      } else {
        this.$message.error(res.msg, 6)
      }
    })
  }

  dbTableEditDrawerOnClose() {
    if (this.dbTableFormSaveContinue) {
      this.dbTableFormSaveContinue = false
      this.dbTableListGetDataSet()
    }
  }

  dbTableDelete() {
    let param: Array<DbTable> = []
    this.dbTableListSelectData.forEach((eo: DbTableVO) => {
      param.push({ id: eo.id } as DbTable)
    })
    this.dbTableStore.removeBatch(this.$toParam<DbTable>(param)).then((res: Res<DbTable>) => {
      if (res.succ) {
        this.$message.success(res.msg, 3)
        this.dbTableListGetDataSet()
      } else {
        this.$message.error(res.msg, 6)
      }
    })
  }

  dbTableDetailDrawerVisible: boolean = false

  dbTableDetailModel: DbTableVO = toDbTableVO()

  dbTableDetailInfo() {
    this.dbTableStore.pkVo(this.$toParam<DbTableQO>({ id: this.dbTableListSelectData[0].id } as DbTableQO)).then((res: Res<DbTableVO>) => {
      if (res.succ) {
        this.dbTableDetailModel = { ...res.data[0] }
        this.dbTableDetailDrawerVisible = true
      } else {
        this.$message.error(res.msg, 6)
      }
    })
  }

  dbTableDetailUpdate() {
    this.dbTableStore.pk(this.$toParam<DbTableQO>({ id: this.dbTableDetailModel.id } as DbTableQO)).then((res: Res<DbTable>) => {
      if (res.succ) {
        this.dbTableFormReset()
        this.dbTableFormModel = { ...res.data[0] }
        this.dbTableDetailDrawerVisible = false
        this.dbTableEditDrawerVisible = true
      } else {
        this.$message.error(res.msg, 6)
      }
    })
  }

  mounted() {
    this.dbTableListGetDataSet()
  }

}
</script>

<style scoped lang="less">

</style>
